package top.kaoshanji.p2ch08c;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * 访问的动态代理处理器
 * author kaoshanji
 * ^_^
 * create time 2025/1/24 17:04
 */
public class AccessInvocationHandler<T> implements InvocationHandler {

    private final T targetObject;

    public AccessInvocationHandler(T targetObject) {
        this.targetObject = targetObject;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        Role annotation = method.getAnnotation(Role.class);
        if (annotation != null) {
            String[] roles = annotation.value();

            // 返回的权限是 staff
            String currentRole = AccessManager.getCurrentUserRole();

            // 权限需要是 manager
            if (!Arrays.asList(roles).contains(currentRole)) {
                throw new RuntimeException("没有调用此方法的权限。");
            }
        }

        return method.invoke(targetObject, args);
    }
}
